package com.example.helloword.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
public class FileUploadController {
    //等价于下面@RequestMapping(value = "/upload",method = RequestMethod.POST)
    @PostMapping("/upload")
    public  String up(String nickname, MultipartFile photo, HttpServletRequest request) throws IOException{
        System.out.println(nickname);
        // 获取图片的原始名称
        System.out.println(photo.getOriginalFilename());
        // 获取文件类型
        System.out.println(photo.getContentType());
        System.out.println(System.getProperty("user.dir"));
        // 获取云端的web服务器,可自定义，也可服务器自动生成临时文件
        //String path = request.getServletContext().getRealPath("/upload/");
        String path = "C:\\Users\\Kevin\\Desktop\\upload\\";
        System.out.println(path);
        saveFile(photo,path);
        return "success upload";
    }

    public void saveFile(MultipartFile photo,String path)throws IOException{
//        判断存储的目录是否存在，如果不存在就创建
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdir();
        }
        File file = new File(path+photo.getOriginalFilename());
        photo.transferTo(file);
    }
}
//如果报错500，后端有问题